package org.skydiveapplibrary.repository;

import org.skydiveapplibrary.data.Database;
import org.skydiveapplibrary.data.LogbookHistory;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class LogbookHistoryRepository
{
	private Database database;
	
	public LogbookHistoryRepository(Context context)
	{
		database = new Database(context);
	}
	
	public LogbookHistory getHistory()
	{
		// init history
		LogbookHistory history = new LogbookHistory();
		history.setFreefallTime(0);
		history.setCutaways(0);

		SQLiteDatabase db = database.getReadableDatabase();
		Cursor cursor = null;
		try
		{
			// perform query
			cursor = db.query(
					Database.LOGBOOK_HISTORY_TABLE,
					Database.LOGBOOK_HISTORY_ALL_COLUMNS,
					null, null, null, null, null);

			if (cursor.moveToFirst())
			{
				history.setFreefallTime(Database.getInteger(cursor, Database.LOGBOOK_HISTORY_FREEFALL_TIME));
				history.setCutaways(Database.getInteger(cursor, Database.LOGBOOK_HISTORY_CUTAWAYS));
			}
		}
		finally
		{
			// close cursor
			if (cursor != null)
			{
				cursor.close();
			}
			// close database
			db.close();
		}
		
		return history;

	}
	
	public void updateHistory(LogbookHistory history)
	{
		// create values
		ContentValues values = new ContentValues();
		values.put(Database.LOGBOOK_HISTORY_FREEFALL_TIME, history.getFreefallTime());
		values.put(Database.LOGBOOK_HISTORY_CUTAWAYS, history.getCutaways());
		
		SQLiteDatabase db = database.getWritableDatabase();
		// start tx
		db.beginTransaction();
		try
		{
			// do an update
			int count = db.update(Database.LOGBOOK_HISTORY_TABLE, values, null, null);
			
			// if no rows updated, do an insert
			if (count <= 0)
			{
				db.insert(Database.LOGBOOK_HISTORY_TABLE, null, values);
			}

			// set tx success
			db.setTransactionSuccessful();
		}
		finally
		{
			// end tx
			db.endTransaction();
			// close db
			db.close();
		}		
	}
}
